package com.itheima.controller;

import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/UserServlet/*")
public class UserServlet extends BaseServlet {
    //登录功能
    private void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取前端页面的用户名密码
        String username = req.getParameter("username");
        String pwd = req.getParameter("pwd");
        String realPath = getServletContext().getRealPath("/txt/user.txt");
        //用户名密码交由service处理,获取返回数据(user对象)
        UserService userService = new UserServiceImpl();
        User user = userService.login(username,pwd,realPath);
        //判断user对象是否为空
        if(user!=null){
            //如果不为空则表示登录成功
            //将登录者的信息保存到session
            req.getSession().setAttribute("user",user);
            //获取复选框的值:1表示记住,其他表示没记住
            String ck = req.getParameter("ck");
            //创建cookie对象
            Cookie cookieName = new Cookie("username",user.getUsername());
            Cookie cookiePwd = new Cookie("pwd",user.getPwd());
            if("1".equals(ck)){
                //实现记住状态
                //设置有效期
                cookieName.setMaxAge(3600);
                cookiePwd.setMaxAge(3600);
            }else {
                //设置有效期
                cookieName.setMaxAge(0);
                cookiePwd.setMaxAge(0);
            }
            //设置存储路径
            cookieName.setPath("/");
            cookiePwd.setPath("/");
            //添加到response对象
            resp.addCookie(cookieName);
            resp.addCookie(cookiePwd);
            //登录成功重定向到首页
            resp.sendRedirect(req.getContextPath()+"/pages/index.jsp");
        }else {
            //如果为空则表示登录失败
            //登录失败重定向到登录页面
            resp.sendRedirect(req.getContextPath()+"/pages/login.jsp");
        }
    }
}
